// 为了0416迭代上线，重构此文件
import React from 'react';
import {connect} from 'react-redux'
import menuRoute from 'routes/menuRoute';
import {Form, Button, Icon, Tabs, message, Popover} from 'antd';
import ResizeTable from 'components/resize-table'
import 'styles/budget-setting/budget-organization/budget-structure/budget-structure-detail.scss';
import ListSelector from 'components/list-selector';
import {messages} from "share/common";
import companyMaintainService from 'containers/enterprise-manage/company-maintain/company-maintain.service';
import antdc from "share/prototype-extend/antd-common";
const TabPane = Tabs.TabPane;

class WrappedCompanyMaintainDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showImportFrame: false,
      saving: false,
      loading: true,
      pagination: {
        current: 1,
        page: 0,
        total: 0,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      selectedRowKeys: [],
      tabs: [
        {
          key: 'BANK',
          name: messages('enterprise-manage.key1'/*银行账户信息*/)
        },
        {
          key: 'USER',
          name: messages('enterprise-manage.key2'/*员工信息*/)
        }
      ],
      data: [],
      tabsData: {
        BANK: {
          rowSelection: null,
          columns:
            [
              {
                title: messages('enterprise-manage.key3'/*银行名称*/),
                dataIndex: 'bankName', width: '15%',
                render: desc => <span><Popover content={desc}>{desc ? desc : "-"}</Popover></span>
              },
              {
                title: messages('enterprise-manage.key4'/*支行名称*/),
                dataIndex: 'bankBranchName',
                width: '15%',
                render: bankBranchName => <span>
                  <Popover content={bankBranchName}>{bankBranchName ? bankBranchName : "-"}</Popover>
                </span>
              },
              {
                title: messages('enterprise-manage.key5'/*国家*/),
                dataIndex: 'country',
                width: '15%',
                render: desc => <span><Popover content={desc}>{desc ? desc : "-"}</Popover></span>
              },
              {
                title: messages('enterprise-manage.key6'/*开户地*/),
                dataIndex: 'bankAddress',
                width: '15%',
              },
              {
                title: messages('enterprise-manage.key7'/*银行详细地址*/),
                dataIndex: 'accountOpeningAddress',
                width: '15%',
                render: desc => <span><Popover content={desc}>{desc ? desc : "-"}</Popover></span>
              },
              {
                title: messages('enterprise-manage.key8'/*银行账户名称*/),
                dataIndex: 'bankAccountName',
                width: '15%',
                render: desc => <span><Popover content={desc}>{desc ? desc : "-"}</Popover></span>
              },
              {
                title: messages('enterprise-manage.key9'/*银行账户账号*/),
                dataIndex: 'bankAccountNumber',
                width: '15%',
                render: desc => <span><Popover content={desc}>{desc ? desc : "-"}</Popover></span>
              },
              {
                title: messages('enterprise-manage.key10'/*开户支行Swift Code*/),
                dataIndex: 'swiftCode',
                width: '12%',
                render: desc => <span><Popover content={desc}>{desc ? desc : "-"}</Popover></span>
              },
              {
                title: messages('enterprise-manage.key11'/*备注*/),
                dataIndex: 'remark',
                width: '15%',
                render: remark => (
                  <Popover content={remark}>
                    {remark ? remark : '-'}
                  </Popover>)
              },
              {
                title: messages('common.operation'),
                dataIndex: 'operation',
                width: '10%',
                render: (text, record) => {
                  return  (<span>{record['_enabled'] && <span>
                    <a onClick={(e) => this.editItem(e, record)}>{messages('common.edit')}</a>
                  </span>}</span>)
                }
              }
            ]
        },
        USER: {
          rowSelection: {
            type: 'checkbox',
            selectedRowKeys: [],
            onChange: this.onSelectChange,
          },
          columns:
            [
              {
                title: messages('enterprise-manage.key12'/*姓名*/),
                key: "fullName",
                dataIndex: 'fullName',
                render: text => antdc.renderPopover(text),
                width: '16%'
              },
              {
                title: messages('enterprise-manage.key13'/*工号*/),
                key: "employeeId",
                dataIndex: 'employeeId',
                render: text => antdc.renderPopover(text),
                width: '8%'
              },
              {
                title: messages('enterprise-manage.key14'/*部门名称*/),
                key: "departmentName",
                dataIndex: 'departmentName',
                render: text => antdc.renderPopover(text),
                width: '10%'
              },
              {
                title: messages('enterprise-manage.key15'/*联系方式*/),
                key: "mobile",
                dataIndex: 'mobile',
                render: text => antdc.renderPopover(text),
              },
              {
                title: messages('enterprise-manage.key16'/*邮箱*/),
                key: "email",
                dataIndex: 'email',
                render: text => antdc.renderPopover(text),
              },
              {
                title: messages('enterprise-manage.key238')/*职位*/,
                key: "position",
                dataIndex: 'position',
                render: text => antdc.renderPopover(text),
              },
              {
                title: messages("common.column.status"),// "状态",
                key: "status",
                dataIndex: 'status',
                render: (text) => {
                  if (text+"" === "1001") {
                    return (<span>
                          <Popover placement="topLeft" content={messages('enterprise-manage.key17'/*在职员工*/)}>
                          {messages('enterprise-manage.key17'/*在职员工*/)}
                          </Popover>
                        </span>)
                  } else if (text+"" === "1002") {
                    return (<span>
                            <Popover placement="topLeft" content={messages('enterprise-manage.key18'/*待离职员工*/)}>
                            {messages('enterprise-manage.key18'/*待离职员工*/)}
                            </Popover>
                          </span>)
                  } else if (text+"" === "1003") {
                    return (<span>
                            <Popover placement="topLeft" content={messages('enterprise-manage.key19'/*离职员工*/)}>
                            {messages('enterprise-manage.key19'/*离职员工*/)}
                            </Popover>
                          </span>)
                  }
                }
              },
            ]
        },
      },
      nowStatus: 'BANK',
      companyDetail:{},
      newBankAccountPage: menuRoute.getRouteItem('new-bank-account', 'key'),                    //新建银行账户
    }
  }

  componentDidMount() {
    this.getCompanyById(this.props.params.companyId);
  }
  getCompanyById = (id) => {
    companyMaintainService.getCompanyById(id)
      .then((res) => {
        this.setState({
          companyDetail: res.data
        },()=>{
          this.getList(this.state.nowStatus);
        })
      })
  }
  //根据tab的key获取对应的列表
  getList = (key) => {
    if (key === 'BANK') {
      this.getBankAccountInfo();
    } else {
      this.getUserInfo();
    }
  };
  //获取银行账户列表
  getBankAccountInfo = () => {
    const {pagination,companyDetail} = this.state;
    let params = {
      page: pagination.page,
      size: pagination.pageSize,
      companyId: this.props.params.companyId
    };
    companyMaintainService.getBankAccountInfo(params)
      .then(response => {
        response.data.map((item, index) => {
          item._enabled = companyDetail.enabled;
          item.key = item.id ? item.id : index;
        });
        pagination.total = Number(response.headers['x-total-count']);
        this.setState({
          data: response.data,
          loading: false,
          pagination
        })
      })
  }
  //获取公司人员
  getUserInfo = () => {
    const {pagination} = this.state;
    let params = {
      page: pagination.page,
      size: pagination.pageSize,
      searchType: "company",
      companyOID: this.props.params.companyOId
    };
    companyMaintainService.getUserInfo(params)
      .then(response => {
        response.data.map((item, index) => {
          item.key = item.id ? item.id : index;
        });
        pagination.total = Number(response.headers['x-total-count']);
        this.setState({
          data: response.data,
          loading: false,
          pagination
        })
      })
  }
  //选项改变时的回调，重置selection
  onSelectChange = (selectedRowKeys, selectedRows) => {
    let {tabsData} = this.state;
    tabsData.USER.rowSelection.selectedRowKeys = selectedRowKeys;
    this.setState({tabsData, selectedRowKeys});
  };

  //编辑
  editItem = (e, record) => {
    let path = this.state.newBankAccountPage.url.replace(":companyOId", this.props.params.companyOId)
      .replace(":companyId", this.props.params.companyId).replace(":flag", record.id);
    this.context.router.push(path);
  };
  //分页点击
  onChangePager = (pagina, filters, sorter) => {
    let {pagination, nowStatus} = this.state;
    pagination.page = pagina.current - 1;
    pagination.current = pagina.current;
    pagination.pageSize = pagina.pageSize;
    this.setState({
      loading: true,
      pagination
    }, () => {
      this.getList(nowStatus);
    })
  };

  //渲染Tabs
  renderTabs = () => {
    return (
      this.state.tabs.map(tab => {
        return <TabPane tab={tab.name} key={tab.key}/>
      })
    )
  };

  //点击
  onChangeTabs = (key) => {
    let {pagination} = this.state;
    pagination.page = 0;
    pagination.pageSize = 10;
    this.setState({
      nowStatus: key,
      loading: true,
      pagination,
      data: [],
    }, () => {
      this.getList(key);
    })

  };

  //新建
  handleNew = () => {
    let path = this.state.newBankAccountPage.url.replace(":companyOId", this.props.params.companyOId)
      .replace(":companyId", this.props.params.companyId).replace(":flag", 'create');
    this.context.router.push(path);
  };

  //返回
  handleBack = () => {
    this.context.router.goBack();
  };

  //渲染按钮
  renderButton = () => {
    const {saving, pagination, selectedRowKeys,nowStatus, companyDetail} = this.state;

    if (nowStatus === "USER") {
      return (
        <div>
          <div className="table-header-title">
            {/*共 {pagination.total} 条数据 / 已经选择了 {this.state.selectedRowKeys.length} 条数据*/}
            {messages("common.total1",{total:pagination.total})}/
            {messages("common.total.selected",{total:this.state.selectedRowKeys.length})}
          </div>
          <div className="table-header-buttons">
            <Button onClick={this.removeUser}
                    disabled={selectedRowKeys.length <= 0}>
              {messages("common.move")}
            </Button>
          </div>
        </div>
      )
    } else {
      return (
        <div>
          <div className="table-header-title">
            {/*共 {pagination.total} 条数据*/}
            {messages("common.total1",{total:pagination.total})}
          </div>
          <div className="table-header-buttons">
            <Button type="primary"
                    disabled={!companyDetail.enabled}
                    onClick={this.handleNew}
                    loading={saving}>
              {messages('common.create')}
            </Button>
          </div>
        </div>
      )
    }
  };

  //确认移动员工
  submitHandle = (value) => {
    const companyOIDTo = value.result[0].companyOID;
    const {selectedRowKeys,nowStatus} = this.state;
    let params = {
      companyOIDTo: companyOIDTo,
      userJobsIds: selectedRowKeys,
    };
    this.setState({
      loading: true
    })
    companyMaintainService.movePersonToCompany(params)
      .then((res) => {
        message.success(messages('common.operate.success'));
        this.getList(nowStatus);
        this.setState({
          selectedRowKeys: [],
          loading: true
        })
        this.showImport(false)
      })
      .catch(()=>{
        this.setState({
          loading: false
        })
      })
  };

  //员工移动
  removeUser = () => {
    this.showImport(true)
  };

  showImport = (value) => {
    this.setState({
      showImportFrame: value
    })
  };

  cancelHandle = () => {
    this.showImport(false)
  };

  render() {
    const {
      tabsData,
      loading,
      pagination,
      nowStatus,
      data,
      showImportFrame
      } = this.state;

    return (
      <div>
        <Tabs onChange={this.onChangeTabs} style={{marginTop: 20}}>
          {this.renderTabs()}
        </Tabs>
        <div className="table-header">
          {this.renderButton()}
        </div>
        <ResizeTable
          columns={tabsData[nowStatus].columns}
          dataSource={data}
          pagination={pagination}
          onChange={this.onChangePager}
          loading={loading}
          bordered
          size="middle"
          rowKey={(reCode) => {
            return reCode.id
          }}
          rowSelection={tabsData[nowStatus].rowSelection}
        />
        <a style={{fontSize: '14px', paddingBottom: '20px'}} onClick={this.handleBack}>
          <Icon type="rollback" style={{marginRight: '5px'}}/>
          {messages('common.back')}
        </a>
        <ListSelector visible={showImportFrame}
                      onOk={this.submitHandle}
                      onCancel={this.cancelHandle}
                      confirmLoading={loading}
                      type='available_company'
                      single={true}
                      extraParams={{"versionId": this.props.params.versionId}}/>
      </div>
    )
  }

}

WrappedCompanyMaintainDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {}
}

const CompanyMaintainDetail = Form.create()(WrappedCompanyMaintainDetail);

export default connect(mapStateToProps)(CompanyMaintainDetail);
